﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Security.Principal;

public partial class Account_Login : PageBase
{
    protected void Page_Init(object sender, EventArgs e)
    {
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (Request.IsAuthenticated)
                {
                    var tag = Request.QueryString["tag"];
                    if (tag == "logout")
                    {
                        FormsAuthentication.SignOut();
                        Session.Abandon();

                        // clear authentication cookie
                        HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
                        cookie1.Expires = DateTime.Now.AddYears(-1);
                        Response.Cookies.Add(cookie1);

                        // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
                        HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
                        cookie2.Expires = DateTime.Now.AddYears(-1);
                        Response.Cookies.Add(cookie2);

                        Response.Redirect("~/Account/Login.aspx");
                    }
                }
            }
            catch (Exception ex) { }
        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string username = Convert.ToString(txtUserName.Text).Trim();
            string password = CryptographicHelper.GetMd5Hash(Convert.ToString(txtPassword.Text).Trim());

            DataResponse<bool?> loginResponse = AuthManager.IsUserLoginValid(username, password);

            if (loginResponse != null)
            {
                if (string.IsNullOrEmpty(loginResponse.ErrorCode))
                {
                    if (loginResponse.Result.HasValue && loginResponse.Result.Value)
                    {
                        DataResponse<User> userResponse = UserManager.GetUser(username);

                        if (userResponse != null)
                        {
                            if (string.IsNullOrEmpty(userResponse.ErrorCode))
                            {
                                if (userResponse.Result != null)
                                {
                                    CreateAuthenticationTicket(userResponse.Result);

                                    loginMessage.Visible = true;
                                    loginMessage.InnerHtml = string.Format("Log in successfull!", loginResponse.ErrorCode);
                                    loginMessage.Attributes.Add("class", "success");
                                }
                                else
                                {
                                    ConfigureInvalidLogError();
                                }
                            }
                            else
                            {
                                ConfigureSpecificLoginError(userResponse.ErrorCode);
                            }
                        }
                        else
                        {
                            ConfigureGeneralLoginError();
                        }
                        
                    }
                    else
                    {
                        ConfigureInvalidLogError();
                    }
                }
                else
                {
                    ConfigureSpecificLoginError(loginResponse.ErrorCode);
                }
            }
            else
            {
                ConfigureGeneralLoginError();
            }
        }
    }

    private void ConfigureGeneralLoginError()
    {
        loginMessage.Visible = true;
        loginMessage.InnerHtml = "Log in failed, unexpected error ocurred.";
        loginMessage.Attributes.Add("class", "error");
    }

    private void ConfigureInvalidLogError()
    {
        loginMessage.Visible = true;
        loginMessage.InnerHtml = string.Format("Log in failed, username or password is incorrect");
        loginMessage.Attributes.Add("class", "error");
    }

    private void ConfigureSpecificLoginError(string errorCode)
    {
        loginMessage.Visible = true;
        loginMessage.InnerHtml = string.Format("Log in failed, unexpected error ocurred [{0}]", errorCode);
        loginMessage.Attributes.Add("class", "error");
    }

    private void CreateAuthenticationTicket(User user)
    {
        SessionHelper.UserInfo = user;

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,
            user.Username,
            DateTime.Now,
            DateTime.Now.AddMinutes(60),
            false,
            string.Empty,
            FormsAuthentication.FormsCookiePath);

        // Encrypt the ticket.
        string encTicket = FormsAuthentication.Encrypt(ticket);

        // Create the cookie.
        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

        // Redirect back to original URL.
        Response.Redirect(FormsAuthentication.GetRedirectUrl(user.Username, false));
    }
}
